/**
 1s 计数器
**/
module cnt1s
#(
    parameter CNT_1S_MAX=50000000,
    parameter CNT_OUTDATA_MAX=1000000
)
(
   input  clk,
   input  rst_n,
   input  en,      //1:使能 0:禁止
   input[29:0]      din_initData,//初始值
   input din_dir,//方向：1:递增 0:递减
   output[29:0] dout_data //输出值
);



reg[29:0] cnt_1s;
wire  cnt_1s_add;
wire  cnt_1s_end;
assign cnt_1s_add = en;
assign cnt_1s_end = cnt_1s_add && cnt_1s== CNT_1S_MAX-1;
always@(posedge clk or negedge rst_n) begin
    if(!rst_n)
        cnt_1s <= 10'b0;
    else if(cnt_1s_add) begin
        if(cnt_1s_end)
            cnt_1s <= 10'b0;
        else
      		cnt_1s <= cnt_1s + 1;
    end
end




reg [29:0]  cnt_outdata=0;
wire        cnt_outdata_add;
wire        cnt_outdata_end;
assign      cnt_outdata_add=cnt_1s_end;
assign      cnt_outdata_end = cnt_outdata_add && cnt_outdata== CNT_OUTDATA_MAX-1;

always @(posedge clk or negedge rst_n)begin
	if(!rst_n)begin
	    if(din_dir)
	        cnt_outdata <= din_initData;
		else
		    cnt_outdata <= CNT_OUTDATA_MAX-cnt_outdata;
	end
	else if(cnt_outdata_add)begin
		if(cnt_outdata_end)
			cnt_outdata <= 0;
		else
			cnt_outdata <= cnt_outdata + 1;
	end
end

assign dout_data=din_dir==1?cnt_outdata : CNT_OUTDATA_MAX-cnt_outdata;

endmodule
